<template>
  <div>
    <div class="product_box">
      <a-card style="width: 100% ;height:100%">
        <div slot="title">
          <a-form layout="inline" :form="form">
            <a-form-item>
              <a-select v-model="searchType" style="width: 120px" placeholder="请选择条件">
                <a-select-option value="productName" key="name">按名称搜索</a-select-option>
                <a-select-option value="productDesc" key="desc">按描述搜索</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input v-model="searchName" placeholder="关键词"></a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchFormSubmit">搜索</a-button>
            </a-form-item>
          </a-form>
        </div>
        <a-button type="primary" slot="extra" @click="toAddProduct">添加商品</a-button>
        <div class="table_box">
          <a-table
            bordered
            :loading="loading"
            :dataSource="products"
            :columns="columns"
            :pagination="{defaultPageSize: 3, showQuickJumper: true, total:total ,current:current}"
            @change="pageChange"
          >
            <template slot="name" slot-scope="text, record">
              <editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)" />
            </template>
            <template slot="status" slot-scope="text, record">
              <a-button
                type="primary"
                @click="updataProductStatus(record)"
              >{{record.status==1?'下架':'上架'}}</a-button>&nbsp;&nbsp;
              <span>({{record.status==1?'在售':'已下架'}})</span>
            </template>
            <template slot="operation" slot-scope="text, record">
              <a-button type="primary" @click="toDetailOrUpdate(record,0)">详情</a-button>&nbsp;&nbsp;
              <a-button type="primary" @click="toDetailOrUpdate(record,1)">更新</a-button>
            </template>
          </a-table>
        </div>
      </a-card>
    </div>
  </div>
</template>
<script>
import EditableCell from "../EditableCell";
import {
  reqProducts,
  reqUpdateStatus,
  reqSearchProducts
} from "../../../api/index";
import { message } from "ant-design-vue";

export default {
  components: {
    EditableCell
  },
  data() {
    return {
      pageSize: 3,
      total: 0, // 商品的总数量
      products: [], // 商品的数组
      loading: false, // 是否正在加载中
      searchName: "", // 搜索的关键字
      searchType: "productName", // 根据哪个字段搜索
      current: 1,
      dataSource: [],
      count: 2,
      columns: [
        {
          title: "商品",
          dataIndex: "name",
          width: "20%"
        },
        {
          title: "商品描述",
          dataIndex: "desc",
          width: "35%"
        },
        {
          title: "价格",
          dataIndex: "price",
          width: "15%"
        },
        {
          title: "状态",
          dataIndex: "status",
          width: "15%",
          scopedSlots: { customRender: "status" }
        },
        {
          title: "操作",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
          width: "15%"
        }
      ]
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
  },
  created() {
    this.reqProducts();
  },
  methods: {
    //去详情页面  或者  更新页面   type :0 代表去详情界面   1：代表去更新界面
    toDetailOrUpdate(record, type) {
      // console.log(record.status);
      var index;
      this.products.forEach((item, i) => {
        if (item.key == record.key) {
          index = i;
        }
      });
      var product = this.products[index];
      // routeName :路由名   type :0 代表去详情界面   1：代表去更新界面
      var routeName = type?"productAddupdate":"productDetail"  
      this.$router.push({    //使用this.$router跳转路由通过params 的时候不能能使用path 应该使用name路由名
        name: routeName,
        params: { product: product }
      });

     
    },
    //点击分页栏的时候触发
    async pageChange(pagination, filters, sorter) {
      // current: 2 // defaultPageSize: 3 // pageSize: 3 // showQuickJumper: true // total: 9
      this.loading = true;
      var { current, defaultPageSize, pageSize } = pagination;
      this.current = current;
      var searchType = this.searchType;
      var searchName = this.searchName;
      const result = await reqSearchProducts({
        pageNum: current,
        pageSize,
        searchName,
        searchType
      });
      if (result.status == 0) {
        var { list, pageNum, pageSize, total, pages } = result.data;
        this.total = total;
        this.products.splice(0, this.products.length);
        list.forEach((item, index) => {
          var { _id, desc, name, price, status } = item;
          var data = { key: _id, name, desc, price, status, value: item };
          this.products.push(data);
        });
      } else {
      }
      this.loading = false;
    },
    //获取商品列表并更新对应的data
    async reqProducts() {
      this.loading = true;
      const result = await reqProducts(1, 3);
      this.total = result.data.total;
      var list = result.data.list;
      this.products.splice(0, this.products.length);
      list.forEach((item, index) => {
        // var {_id, categoryId, desc, detail, imgs, name, pCategoryId, price, status} = item
        var { _id, desc, name, price, status } = item;
        var data = { key: _id, name, desc, price, status, value: item };
        this.products.push(data);
      });
      this.loading = false;
    },
    //更新商品的状态(上架/下架)
    async updataProductStatus(record) {
      this.loading = true;
      var status = record.status == 1 ? 2 : 1;
      const result = await reqUpdateStatus(record.key, status);
      if (result.status == 0) {
        var newProduct = this.products.map(item => {
          //更新旧数据中的status的值
          if (item.key == record.key) {
            item.status = status;
            item.value.status = status;
          }
          return item;
        });
        this.products.splice(0, this.products.length);
        this.products.push(...newProduct);
        // this.reqProducts() //状态更新成功  重新请求服务器获取最新数据
        message.success("状态更新成功!");
      } else {
        message.error("状态更新失败!");
      }

      this.loading = false;
    },
    //路由跳转到 addupdate
    toAddProduct() {
      this.$router.push("/product/addupdate");
    },
    //搜索按钮提交
    async searchFormSubmit() {
      this.loading = true;

      var pageNum = 1;
      var searchType = this.searchType;
      var searchName = this.searchName;
      var pageSize = this.pageSize;
      const result = await reqSearchProducts({
        pageNum,
        pageSize,
        searchName,
        searchType
      });
      if (result.status == 0) {
        var { list, pageNum, pageSize, total, pages } = result.data;
        this.total = total;
        this.current = 1;
        this.products.splice(0, this.products.length);
        list.forEach((item, index) => {
          var { _id, desc, name, price, status } = item;
          var data = { key: _id, name, desc, price, status, value: item };
          this.products.push(data);
        });
      } else {
        message.error("搜索失败!");
      }

      this.loading = false;
    },
    //修改单元格
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find(item => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    }
  }
};
</script>
<style>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  line-height: 18px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-add-btn {
  margin-bottom: 8px;
}
</style>